package com.gimi.cloud.bbp.common.utils.base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * base64流转换工具
 * @author 李林峰
 * @version 1.0
 * @Description
 * @create 2018年2月6日
 */
public class Base64Util {
	
	/**
	 * Base64编码inStream
	 * @param inStream 待编码的 inStream
	 * @return 编码结果
	 * @throws IOException
	 */
	public static String encoderInputStream(InputStream inStream) throws IOException {
		ByteArrayOutputStream outSteam = null;
		try {
			outSteam = new ByteArrayOutputStream();  
		    byte[] buffer = new byte[1024];  
		    int len = -1;  
		    while ((len = inStream.read(buffer)) != -1) {  
		        outSteam.write(buffer, 0, len);  
		    }
		    inStream.close();
		    byte[] byteArray = outSteam.toByteArray();
		    return Base64.getEncoder().encodeToString(byteArray);
		} finally {
			if (outSteam!=null) {
				outSteam.close();  
			}
			if (inStream!=null) {
				inStream.close();
			}
		}
	}

	/**
	 * Base64解码inStream
	 * @param base64str 待解码的base64字符串
	 * @return 解码结果
	 * @throws IOException
	 */
	public static InputStream dencoderToInputStream(String base64str) throws IOException {
		byte[] decode = Base64.getDecoder().decode(base64str);
		return new ByteArrayInputStream(decode);
	}
}
